package org.opentcs.kcvehicle.communication.kc.udp.agv.param;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.opentcs.kcvehicle.communication.kc.common.CaffeineUtil;
import org.opentcs.kcvehicle.communication.kc.common.byteutils.ByteUtils;

public class AgvEventHeader {


  //常量区域     开始
  //授权码
  public byte[] authorizationCode;
  //header 开始
  //版本号
  public byte versionNum;
  //报文类型 0x00：请求报文 ; 0x01：应答报文
  public byte msgType;
  //request 和 response ，transationId一致,2个字节
  public byte[] transationId;
  //服务码
  public byte serviceCode;
  //命令码，用于区分不同命令，request 和 response 相同
  public byte commandCode;
  //执行码，应答报文填写，表明命令执行情况，请求数据包置 0
  public byte executionCode;
  //保留
  public byte retain;

  //header 结束
  //常量区域     结束


  //request
  public AgvEventHeader(Byte commandCode) {
    this.authorizationCode = AgvEventConstant.AuthorizationCode;
    this.versionNum = AgvEventConstant.VersionNum;
    this.msgType = AgvEventConstant.MSGTypeRequest;

    this.transationId = CaffeineUtil.getUUIDAGV();
    this.serviceCode = 0x10;
    this.commandCode = commandCode;
    this.executionCode = 0x00;
    this.retain = 0x00;
  }

  public AgvEventHeader(byte[] src) {
    this.authorizationCode = ByteUtils.copyOfRange(src, 0, 16);
    this.versionNum = src[16];
    this.msgType = src[17];
    this.transationId = ByteUtils.copyOfRange(src, 18, 20);
    this.serviceCode = src[20];
    this.commandCode = src[21];
    this.executionCode = src[22];
    this.retain = src[23];
  }


  //response
  public AgvEventHeader(Byte serviceCode, Byte commandCode, Byte executionCode) {
    this.authorizationCode = AgvEventConstant.AuthorizationCode;
    this.versionNum = AgvEventConstant.VersionNum;
    this.msgType = AgvEventConstant.MSGTypeResponse;
    this.transationId = CaffeineUtil.getUUIDAGV();
    this.serviceCode = serviceCode;
  }

  public byte[] getTransationId() {
    return transationId;
  }

  public String headerToString() {
    return "AgvEventHeader{" +
        "authorizationCode=" + Arrays.toString(authorizationCode) +
        ", versionNum=" + versionNum +
        ", msgType=" + msgType +
        ", transationId=" + Arrays.toString(transationId) +
        ", serviceCode=" + serviceCode +
        ", commandCode=" + commandCode +
        ", executionCode=" + executionCode +
        ", retain=" + retain +
        '}';
  }

  public List<Byte> getHeaderBytes() {
    List<Byte> bytes = new ArrayList<>();
    //add 授权码
    for (byte b : authorizationCode) {
      bytes.add(b);
    }
    //add 协议版本号
    bytes.add(versionNum);
    //add 报文类型
    bytes.add(msgType);
    //add 报文标识
    for (byte b : transationId) {
      bytes.add(b);
    }
    bytes.add(serviceCode);
    bytes.add(commandCode);
    bytes.add(executionCode);
    bytes.add(retain);
    return bytes;
  }

}
